const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const bodyParser = require('body-parser');
const fs = require('fs');
const net = require('net');
const TCP_PORT = "8001"
const TIMEOUT = 60000;//tcp客户端超过60秒没发数据判为超时并断开连接
let tcpClient = null;//tcp客户端
let IP = '0.0.0.0'
const urlencodeParser = bodyParser.urlencoded({
    extended: true,
    limit: '50mb'
});

//创建TCP服务器
const tcpServer = net.createServer((socket) => {
    //connect
    let addr = socket.address().address + ':' + socket.address().port
    console.log(addr, " connect.")
    socket.addr = addr
    tcpClient = socket

    // recieve data
    socket.on("data", data => {
        // let str = addr + " receive: " + data.toString('ascii')
        let str = addr + " receive: " + data
        console.log(str)
        // socket.lastValue = data.toString('ascii')
        socket.lastValue = data.toString('ascii')
    })
    // socket.lastValue = data.toString('ascii')
    // close
    socket.on('close', () => {
        console.log(addr, "close")
        tcpClient = null;
    })
    socket.on('error', (err) => {
        console.log("error", err)
        tcpClient = null;
    })
    socket.setTimeout(TIMEOUT);
    // 超过一定时间 没接收到数据，就主动断开连接。
    socket.on('timeout', () => {
        console.log(socket.id, socket.addr, 'socket timeout');
        socket.end();
        tcpClient = null;
    });
})

tcpServer.on("error", (err) => {
    console.log(err)
    tcpClient = null;
})

tcpServer.listen({ port: TCP_PORT, host: IP }, () => {
    console.log(' tcp server running on', tcpServer.address())
})

function inituser(temp) {
    let datas = {
        idcard: temp.idcard,
        balance: temp.balance,
    }
    let str1 = datas.idcard.toString()
    let str2 = datas.balance.toString()
    // 向TCP客户端发送1
    if (tcpClient) {
        
        tcpClient.write(str1+str2)
    }
    else {
        console.log("inituser error:not tcpClient.")
    }
}
// 获取数据
function getData() {
    // 获取设备最新数据
    if (tcpClient) {
        let str = tcpClient.lastValue
        console.log(str)
        if(str == undefined){
            return { "msg": "硬件客户端已经连接，请刷卡", "code": "9" }
        }else{
            let temp = ''
            for (let k = 0; k < str.length; k++) {
                if (str[k] != 'i') {
                    temp += str[k]
                }
            }
            let str1 = '', str2 = '';
            for (let i = 0; i < 4; i++) {
                str1 += temp[i]
            }
            for (let j = 4; j < temp.length; j++) {
                str2 += temp[j]
            }

            // return tcpClient.lastValue
            return {
                "idcard": str1,
                "balance": str2
            }
        }
        
    }
    else {
        return {"msg":"硬件客户端未连接，或出错，请检查硬件设备","code":"0"}
    }
}

//-------------------------------------------------
const connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: '12345678',
    database: 'internetcafe'
});
connection.connect(function (err) {
    if (err) {
        console.error('连接失败: ' + err.stack);
        return;
    }
    console.log('连接成功 id ' + connection.threadId);
})
router.get("/data", (req, res) => {
    res.json(getData())
})
//查询所有用户
router.get("/selectuser", function (req, res) {
    connection.query('select * from user', function (err, result) {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else {
            res.jsonp({
                result: result,
            })
        }
    })
});
//查询用户数量
router.get("/selectusercount", function (req, res) {
    connection.query('select count(*) count from user', function (err, rows, result) {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else {
            res.jsonp({
                result: rows[0].count,
            })
        }
    })
});

router.get("/selectoneuser", function (req, res) {
    let data = req.query
    console.log(data.kindid)
    connection.query('select * from user where ismember=  "' + data.kindid + '"  ', function (err, result) {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else {
            res.jsonp({
                result: result,
            })
        }
    })
});
router.get("/selectuserByIdcard", function (req, res) {
    let data = req.query
    connection.query('select * from user where idcard=  "' + data.idcard + '"  ', function (err, result) {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else {
            res.jsonp({
                result: result,
            })
        }
    })
});
router.get("/selectuserById", function (req, res) {
    let data = req.query
    connection.query('select * from user where id=  "' + data.id + '"  ', function (err, result) {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else {
            res.jsonp({
                result: result,
            })
        }
    })
});
router.get('/adduser', (req, res) => {
    // inituser({idcard:1312,balance:1232})

    //    return;
    let data = req.query;
    console.log(data)
    let tempdata = {
        id: null,
        username: data.username,
        pwd: data.pwd,
        idcard: data.idcard,
        balance: data.balance,
        ismember: data.ismember,
    }
    //检验是否为空
    if (tempdata.id == '' || tempdata.username == '' || tempdata.pwd == '' || tempdata.idcard == '') {
        res.jsonp({
            code: 0,
            msg: '你输入信息不能为空。'
        })
        return;
    }
    connection.query('select * from user where idcard=  "' + tempdata.idcard + '"  ', (err, result) => {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else if (result[0] != null) {
            res.jsonp({
                msg: "该卡号的用户已经存在",
                code: 0
            })
        } else {
            if(tcpClient){
                connection.query('insert into user set ?', tempdata, (err, result) => {
                    if (err) {
                        console.log(err);
                        res.jsonp({
                            fail: 1
                        })
                    } else {
                        res.jsonp({
                            code: 1,
                            result: data
                        })
                        inituser(tempdata)
                        // inituser(tempdata)
                    }
                })
            }else{
                res.jsonp({
                    msg: "请开启硬件设备，或检查TCP连接情况",
                    code: 0
                })
            }
        }
    })
})
//修改用户信息
router.get('/updateuser', function (req, res) {
    let data = req.query
    console.log(req.query)
    // console.log(window.location.search)
    // return;
    let tempdata = {
        id: data.id,
        username: data.username,
        pwd: data.pwd,
        idcard: data.idcard,
        balance: data.balance,
        ismember: data.ismember,
        // allcomsume: null,
    }
    //检验是否为空
    if (tempdata.id == '' || tempdata.username == '' || tempdata.pwd == '' || tempdata.idcard == '') {
        res.jsonp({
            code: 0,
            msg: '你输入信息不能为空。'
        })
        return;
    } else {
        connection.query('update user set ? where id =  "' + tempdata.id + '" ', tempdata, function (err, result) {
            if (err) {
                console.log
                res.jsonp({
                    fail: 1
                });
            } else {
                res.jsonp({
                    code: 1,
                })
            }
        });
    }
});
//用户充值
router.get("/adduserbalance", function (req, res) {
    let data = req.query
    let temp = {
        idcard: data.idcard,
        balance: parseInt(data.balance) + parseInt(data.money)
    }
    if (data.money == '') {
        res.jsonp({
            code: 0,
            msg: '充值金额不能为空'
        })
        return;
    } else {
        if(tcpClient){
            connection.query('update  user set balance= "' + temp.balance + '" where idcard="' + temp.idcard + '" ', function (err, result) {
                if (err) {
                    console.log(err);
                    res.jsonp({
                        fail: 1
                    })
                } else {
                    res.jsonp({
                        code: 1,
                        msg: '恭喜：充值成功,是否退出'
                    })
                    inituser(temp)

                }
            })
        }else{
            res.jsonp({
                msg: "请开启硬件设备，或检查TCP连接情况",
                code: 0
            })
        }
       
    }
});
//扣除费用
router.get("/minususerbalance", (req, res) => {
    let data = req.query
    console.log(data);

    if (data.other == ''||data.computertime=='') {
        res.jsonp({
            code: 0,
            msg: '输入信息不能为空'
        })
        return;
    }
    let time
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    time = year + '/' + month + '/' + day + '/ ' + hour + ':' + minute + ':' + second

    let total = parseInt(data.other) + (parseInt(data.computertime) * parseInt(data.price))
    let balance = parseInt(data.balance) - total
    if (balance < 0) {
        res.jsonp({
            code: 0,
            msg: "余额不足"
        })
        return;
    } else {
        let temp = {
            idcard: data.idcard,
            balance: balance
        }
        let tempsql = {
            consumeid: null,
            date: time,
            userid: data.userid,
            computerid: data.no,
            computertime: data.computertime,
            other: data.other,
            total: total
        }
        // console.log(tempsql)
        // return
        connection.query('insert into consume set ? ',tempsql, function (err, result) {
            if (err) {
                console.log(err);
                res.jsonp({
                    fail: 1
                })
            } else {
                if(tcpClient){
                    connection.query('update  user set balance= "' + temp.balance + '" where idcard="' + temp.idcard + '" ', function (err, result) {
                        if (err) {
                            console.log(err);
                            res.jsonp({
                                fail: 1
                            })
                        } else {
                            res.jsonp({
                                code: 1,
                                msg: '恭喜：交易成功,欢迎下次光临'
                            })
                            inituser(temp)
                        }
                    })
                }else{
                    res.jsonp({
                        msg: "请开启硬件设备，或检查TCP连接情况",
                        code: 0
                    })
                }
            }
        })
    }
});
router.get("/deluser", function (req, res) {
    let data = req.query
    console.log(data.id)
    connection.query('delete from  user where id=  "' + data.id + '"  ', function (err, result) {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else {
            res.jsonp({
                result: result,
                code: 1,
                msg: '删除成功。'
            })
        }
    })
});
module.exports = router;